// ui/components/ChatMessageItem.js
// Assuming ElementPlus, MarkdownIt, hljs are globally available or handled elsewhere.

export default {
  name: 'ChatMessageItem',
  props: {
    message: {
      type: Object, // TypeScript equivalent was PropType<ChatMessageModel>
      required: true
      // JSDoc for reference:
      /** 
       * @type {{
       *   message_id: string;
       *   participant_id: string;
       *   sender_nickname: string;
       *   content: string; // Markdown
       *   raw_content?: string;
       *   timestamp: string; 
       *   tags: string[];
       *   observed_tags?: string[];
       *   raw_llm_output_if_agent?: string;
       * }}
       */
    },
    isCurrentUser: {
      type: Boolean,
      required: true
    }
  },
  emits: ['copy-text-requested', 'tag-clicked'],
  setup(props, { emit }) {
    const { computed } = Vue; // Vue is global

    let md;
    // Attempt to use globally available MarkdownIt and hljs
    if (typeof MarkdownIt !== 'undefined') {
        md = new MarkdownIt({
            html: true,
            linkify: true,
            typographer: true,
            highlight: function (str, lang) {
                if (typeof hljs !== 'undefined' && lang && hljs.getLanguage(lang)) {
                    try {
                        return '<pre class="hljs"><code>' +
                               hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                               '</code></pre>';
                    } catch (__) {}
                }
                // Fallback for md.utils.escapeHtml if md is the basic fallback
                const escapeHtml = md.utils ? md.utils.escapeHtml : (s) => s.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]));
                return '<pre class="hljs"><code>' + escapeHtml(str) + '</code></pre>';
            }
        });
    } else {
        console.warn('ChatMessageItem: MarkdownIt library is not available. Markdown rendering will be basic (no HTML, no highlighting).');
        md = {
            render: (text) => String(text || '').replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m])),
            utils: { escapeHtml: (s) => String(s || '').replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m])) }
        };
    }

    const renderedMarkdownContent = computed(() => {
      return md.render(props.message.content || '');
    });

    const formattedTimestamp = computed(() => {
      try {
        const date = new Date(props.message.timestamp);
        const today = new Date();
        
        const isToday = date.getFullYear() === today.getFullYear() &&
                      date.getMonth() === today.getMonth() &&
                      date.getDate() === today.getDate();

        if (isToday) {
          return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
        } else {
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          const time = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
          return `${month}-${day} ${time}`;
        }
      } catch (e) {
        console.error("Error formatting timestamp:", e, "Raw timestamp:", props.message.timestamp);
        return String(props.message.timestamp || ''); // Fallback to raw timestamp if parsing fails
      }
    });

    function handleCopyText() {
      const textToCopy = props.message.raw_llm_output_if_agent || props.message.content;
      const ElMessage = window.ElementPlus?.ElMessage;

      if (navigator.clipboard && textToCopy) {
        navigator.clipboard.writeText(textToCopy)
          .then(() => {
            if(ElMessage) ElMessage.success('原始文本已复制');
            else console.log('原始文本已复制 (ElMessage not found)');
          })
          .catch(err => {
            console.error('Failed to copy text using navigator.clipboard:', err);
            emit('copy-text-requested', props.message.message_id);
            if(ElMessage) ElMessage.warning('复制到剪贴板失败，尝试通过后端复制');
            else console.warn('复制到剪贴板失败 (ElMessage not found)');
          });
      } else if (textToCopy) {
        emit('copy-text-requested', props.message.message_id);
        if(ElMessage) ElMessage.info('正在请求复制文本...');
        else console.log('正在请求复制文本... (ElMessage not found)');
      } else {
        if(ElMessage) ElMessage.error('没有可复制的文本内容');
        else console.error('没有可复制的文本内容 (ElMessage not found)');
      }
    }

    function handleTagClick(tag) {
      emit('tag-clicked', tag);
    }

    return {
      renderedMarkdownContent,
      formattedTimestamp,
      handleCopyText,
      handleTagClick,
    };
  },
  template: `
  <div class="chat-message-item" :class="{ 'current-user': isCurrentUser, 'other-user': !isCurrentUser }">
    <div class="message-bubble">
      <div class="message-header">
        <span class="sender-nickname">{{ message.sender_nickname }}</span>
        <span class="timestamp">{{ formattedTimestamp }}</span>
      </div>
      <div class="message-content" v-html="renderedMarkdownContent"></div>
      <div v-if="message.tags && message.tags.length > 0" class="message-tags">
        <el-tooltip
          v-for="tag in message.tags"
          :key="tag"
          :content="\`筛选标签: \${tag}\`"
          placement="top"
        >
          <el-tag
            type="info"
            size="small"
            effect="light"
            @click.stop="handleTagClick(tag)"
            class="tag-item"
          >
            #{{ tag }}
          </el-tag>
        </el-tooltip>
      </div>
      <div class="message-actions">
        <el-tooltip content="复制原始文本" placement="top">
          <el-button
            type="text"
            size="small"
            icon="CopyDocument"
            @click="handleCopyText"
            class="action-button"
          />
        </el-tooltip>
      </div>
    </div>
  </div>
  `
};